package com.cuiweiyou.gimmick;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URI;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.filechooser.FileNameExtensionFilter;

public class GimmickUI extends JFrame {
    private GimmickMaster gimmickMaster;

    private int frameWidth;
    private int frameHeight;

    private DefaultListCellRenderer listCellRenderer;

    private JList othersideListView;
    private JTextArea nextGimmickTextArea;

    private JButton resetLastGimmicksButton;
    private JButton saveGimmickButton;
    private JButton loadGimmickButton;
    private JButton chattestButton;
    private JButton clearButton;
    private JButton okButton;

    private JTable gimmickTable;

    private JRadioButton otherSideRadioBtn;
    private JRadioButton meSideRadioBtn;
    private JScrollPane otherGimmickListViewPanel;

    public GimmickUI() {
        super("话术制作GimmickMaker");
        setDefaultLookAndFeelDecorated(true);
        Dimension dimension = Toolkit.getDefaultToolkit()
                                     .getScreenSize();
        frameWidth = (int) (dimension.getWidth() / 4 * 3);
        frameHeight = (int) (dimension.getHeight() / 4 * 3);
        int x = (int) (dimension.getWidth() / 2 - frameWidth / 2);
        int y = (int) (dimension.getHeight() / 2 - frameHeight / 2);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocation(x, y);
        setSize(frameWidth, frameHeight);

        initView();

        setVisible(true);
    }

    public void setOnLoadGimmicksListener(final OnLoadGimmicksListener listener) {
        loadGimmickButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                List<GimmickBean> list = gimmickMaster.getAllGimmicks();
                if (null != list && list.size() > 0) {
                    JOptionPane.showConfirmDialog(GimmickUI.this, "请先保存已有话术", "提示", JOptionPane.YES_OPTION);
                    return;
                }

                gotoSelectGimmickFile(listener);
            }
        });
    }

    public void setOnSaveGimmicksListener(final OnSaveGimmicksListener listener) {
        saveGimmickButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                gotoSaveGimmicks(listener);
            }
        });
    }

    public void setOnChattestListener(final OnChattestListener listener) {
        chattestButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                gotoChattest(listener);
            }
        });
    }

    public void setOnTableItemSelectedListener(final OnTableItemSelectedListener listener) {
        gimmickTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (MouseEvent.BUTTON3 == e.getButton()) {
                    if (1 == e.getClickCount()) {
                        gotoGetSelectedGimmick(e, listener);
                    }
                }
            }
        });
    }

    public void setOnListViewItemSelectedListener(final OnListViewItemSelectedListener listener) {
        othersideListView.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (MouseEvent.BUTTON3 == e.getButton()) {
                    if (1 == e.getClickCount()) {
                        gotoGetSelectedOtherSideGimmick(e, listener);
                    }
                }
            }
        });
    }

    public void setOnRestLastGimmicksListener(final OnResetLastGimmicksListener listener) {
        resetLastGimmicksButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                gotoRestLastGimmicks(listener);
            }
        });
    }

    public void setOnInsertGimmickListener(final OnInsertGimmickListener listener) {
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                gotoInsertGimmick(listener);
            }
        });
    }

    public void setOnSideItemSelectedListener(final OnSideItemSelectedListener listener) {
        otherSideRadioBtn.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent itemEvent) {
                if (null != listener) {
                    if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
                        listener.onSideItemSelected("O");
                    }
                }
            }
        });
        meSideRadioBtn.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent itemEvent) {
                if (null != listener) {
                    if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
                        listener.onSideItemSelected("M");
                    }
                }
            }
        });
    }

    public void setOnClearGimmickListViewListener(final OnClearGimmickListViewListener listener) {
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                gotoClearGimmickListView(listener); // 清空按钮
            }
        });
    }

    public JTable getGimmickTable() {
        return gimmickTable;
    }

    private void initView() {
        int titleBarWidth = frameWidth;
        int titleBarHeight = 35;
        int separatorWidth = frameWidth;
        int separatorHeight = 3;
        int gimmickPanelWidth = frameWidth;
        int gimmickPanelHeight = frameHeight - titleBarHeight - separatorHeight;

        Box verticalBox = Box.createVerticalBox();

        verticalBox.add(getTitleBarPanel(titleBarWidth, titleBarHeight));
        //verticalBox.add(getSeparator(separatorWidth, separatorHeight, Color.WHITE));
        verticalBox.add(getGimmickPanel(gimmickPanelWidth, gimmickPanelHeight));

        setContentPane(verticalBox);
    }

    private Component getTitleBarPanel(int panelWidth, int panelHeight) {
        int loadBtnWidth = 120;
        int loadBtnHeight = 30;
        int saveBtnWidth = 120;
        int saveBtnHeight = 30;
        int chatBtnWidth = 120;
        int chatBtnHeight = 30;
        int aboutBtnWidth = 30;
        int aboutBtnHeight = 30;
        int emptyWidth = panelWidth - loadBtnWidth - saveBtnWidth - chatBtnWidth - aboutBtnWidth - 30;
        int emptyHeight = 30;

        loadGimmickButton = new JButton("加载话术");
        loadGimmickButton.setPreferredSize(new Dimension(loadBtnWidth, loadBtnHeight));

        saveGimmickButton = new JButton("保存话术");
        saveGimmickButton.setPreferredSize(new Dimension(saveBtnWidth, saveBtnHeight));

        chattestButton = new JButton("模拟对话");
        chattestButton.setPreferredSize(new Dimension(chatBtnWidth, chatBtnHeight));

        JLabel aboutLabel = new JLabel("关于");
        aboutLabel.setPreferredSize(new Dimension(aboutBtnWidth, aboutBtnHeight));
        aboutLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                super.mouseClicked(mouseEvent);
                browserWebsite();
            }
        });

        JLabel empty = new JLabel();
        empty.setPreferredSize(new Dimension(emptyWidth, emptyHeight));

        Border darkGrayLineBorder = BorderFactory.createLineBorder(Color.DARK_GRAY);

        JPanel titleBarPanel = new JPanel();
        titleBarPanel.setPreferredSize(new Dimension(panelWidth, panelHeight));
        titleBarPanel.setBackground(Color.WHITE);
        titleBarPanel.setBorder(darkGrayLineBorder);
        titleBarPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        titleBarPanel.add(loadGimmickButton);
        titleBarPanel.add(saveGimmickButton);
        titleBarPanel.add(chattestButton);
        titleBarPanel.add(empty);
        titleBarPanel.add(aboutLabel);

        return titleBarPanel;
    }

    private Component getGimmickPanel(int panelWidth, int panelHeight) {
        JPanel gimmickPanel = new JPanel();
        gimmickPanel.setPreferredSize(new Dimension(panelWidth, panelHeight));
        gimmickPanel.setLayout(new BorderLayout());
        gimmickPanel.add(BorderLayout.WEST, getEditGimmickPanel(panelWidth / 3 * 1, panelHeight));
        gimmickPanel.add(BorderLayout.EAST, getGimmickListPanel(panelWidth / 3 * 2, panelHeight));

        return gimmickPanel;
    }

    private Component getEditGimmickPanel(int panelWidth, int panelHeight) {
        int lastGimmickPanelHeight = 33;
        int nextGimmickPanelHeight = 33;
        int lastSeparatorHeight = 5;
        int nextSeparatorHeight = 10;
        int okButtonPanelWidth = panelWidth;
        int okButtonPanelHeight = 33;
        int okButtonWidth = 60;
        int okButtonHeight = 30;
        int sidePanelWidth = okButtonPanelWidth - okButtonWidth;
        int sidePanelHeight = okButtonHeight;
        int otherGimmickListViewHeight = (panelHeight - lastGimmickPanelHeight - nextGimmickPanelHeight - lastSeparatorHeight - nextSeparatorHeight - okButtonPanelHeight) / 2;
        int nextTextAreaPanelHeight = otherGimmickListViewHeight;

        resetLastGimmicksButton = new JButton("清空");

        JLabel lastGimmickLabel = new JLabel("上一句");

        JPanel lastGimmickPanel = new JPanel();
        lastGimmickPanel.setPreferredSize(new Dimension(panelWidth, lastGimmickPanelHeight));
        lastGimmickPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        lastGimmickPanel.add(resetLastGimmicksButton);
        lastGimmickPanel.add(lastGimmickLabel);

        othersideListView = new JList();
        othersideListView.setCellRenderer(getListCellRenderer());
        othersideListView.setModel(new DefaultListModel<String>());
        othersideListView.setFixedCellHeight(30);

        otherGimmickListViewPanel = new JScrollPane(othersideListView);
        otherGimmickListViewPanel.setPreferredSize(new Dimension(panelWidth, otherGimmickListViewHeight));

        JLabel nextGimmickLabel = new JLabel("回复（ “上一句”为空时 此为对话首句 ）");
        nextGimmickLabel.setPreferredSize(new Dimension(panelWidth, nextGimmickPanelHeight));

        JPanel nextGimmickPanel = new JPanel();
        nextGimmickPanel.setPreferredSize(new Dimension(panelWidth, nextGimmickPanelHeight));
        nextGimmickPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        nextGimmickPanel.add(nextGimmickLabel);

        nextGimmickTextArea = new JTextArea();

        JScrollPane nextGimmickTextAreaPanel = new JScrollPane(nextGimmickTextArea);
        nextGimmickTextAreaPanel.setPreferredSize(new Dimension(panelWidth, nextTextAreaPanelHeight));

        otherSideRadioBtn = new JRadioButton("对方语句 O");
        meSideRadioBtn = new JRadioButton("己方语句 M");
        meSideRadioBtn.setSelected(true);
        ButtonGroup sideGroup = new ButtonGroup();
        sideGroup.add(otherSideRadioBtn);
        sideGroup.add(meSideRadioBtn);

        JPanel sidePanel = new JPanel();
        sidePanel.setPreferredSize(new Dimension(sidePanelWidth, sidePanelHeight));
        //sidePanel.setBorder(BorderFactory.createTitledBorder("话术所属"));
        sidePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        sidePanel.add(otherSideRadioBtn);
        sidePanel.add(meSideRadioBtn);

        okButton = new JButton("记录");
        okButton.setPreferredSize(new Dimension(okButtonWidth, okButtonHeight));

        JPanel okButtonPanel = new JPanel();
        okButtonPanel.setLayout(new BoxLayout(okButtonPanel, BoxLayout.X_AXIS));
        okButtonPanel.setPreferredSize(new Dimension(okButtonPanelWidth, okButtonPanelHeight));
        okButtonPanel.add(sidePanel);
        okButtonPanel.add(okButton);

        JPanel editGimmickPanel = new JPanel();
        editGimmickPanel.setPreferredSize(new Dimension(panelWidth, panelHeight));
        editGimmickPanel.setBackground(Color.WHITE);
        editGimmickPanel.setLayout(new BoxLayout(editGimmickPanel, BoxLayout.Y_AXIS));
        editGimmickPanel.add(getSeparator(panelWidth, lastSeparatorHeight, Color.WHITE));
        editGimmickPanel.add(lastGimmickPanel);
        editGimmickPanel.add(otherGimmickListViewPanel);
        editGimmickPanel.add(getSeparator(panelWidth, nextSeparatorHeight, Color.WHITE));
        editGimmickPanel.add(nextGimmickPanel);
        editGimmickPanel.add(nextGimmickTextAreaPanel);
        editGimmickPanel.add(okButtonPanel);

        return editGimmickPanel;
    }

    private Component getGimmickListPanel(int panelWidth, int panelHeight) {
        int clearButtonWidth = 60;
        int clearButtonHeight = 35;
        int listViewPanelWidth = panelWidth;
        int listViewPanelHeight = panelHeight - clearButtonHeight;

        gimmickTable = new GimmickTable();
        gimmickTable.getTableHeader()
                    .setReorderingAllowed(false);
        gimmickTable.getTableHeader()
                    .setFont(new Font("宋体", Font.BOLD, 16));
        gimmickTable.setRowHeight(gimmickTable.getRowHeight() + 15);

        JScrollPane gimmickTablePanel = new JScrollPane(gimmickTable);
        gimmickTablePanel.setPreferredSize(new Dimension(listViewPanelWidth, listViewPanelHeight));
        gimmickTablePanel.setBackground(Color.WHITE);

        clearButton = new JButton("清除");

        JPanel clearButtonPanel = new JPanel();
        clearButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        clearButtonPanel.setPreferredSize(new Dimension(clearButtonWidth, clearButtonHeight));
        clearButtonPanel.add(clearButton);

        JPanel targetPanel = new JPanel();
        targetPanel.setPreferredSize(new Dimension(panelWidth, panelHeight));
        targetPanel.setBackground(Color.WHITE);
        targetPanel.setLayout(new BoxLayout(targetPanel, BoxLayout.Y_AXIS));
        targetPanel.add(gimmickTablePanel);
        targetPanel.add(clearButtonPanel);

        return targetPanel;
    }

    private Component getSeparator(int separatorWidth, int separatorHeight, Color color) {
        JSeparator separator = new JSeparator(SwingConstants.CENTER);
        separator.setPreferredSize(new Dimension(separatorWidth, separatorHeight));
        separator.setBackground(Color.WHITE);
        separator.setForeground(color);

        return separator;
    }

    private void gotoSelectGimmickFile(OnLoadGimmicksListener listener) {
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setDialogTitle("请选择已有的话术文件");
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            if (null != file) {
                String filePath = file.getAbsolutePath();
                if (null != listener) {
                    listener.onLoadGimmicks(filePath);
                    flushOtherSideGimmickListView();
                }
            } else {
                JOptionPane.showMessageDialog(null, "请选择已有的话术文件");
            }
        } else {
            JOptionPane.showMessageDialog(null, "请选择已有的话术文件");
        }
    }

    private void gotoRestLastGimmicks(OnResetLastGimmicksListener listener) {
        if (null != listener) {
            listener.onResetLastGimmicks();
            ((DefaultListModel) othersideListView.getModel()).removeAllElements();
        }
    }

    private void gotoChattest(OnChattestListener listener) {
        if (null != listener) {
            List<GimmickBean> allGimmicks = gimmickMaster.getAllGimmicks();
            listener.onChattest(allGimmicks);
        }
    }

    private void gotoSaveGimmicks(OnSaveGimmicksListener listener) {
        List<GimmickBean> list = gimmickMaster.getAllGimmicks();
        if (list.size() < 1) {
            JOptionPane.showMessageDialog(null, "没有话术内容");
            return;
        }

        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        chooser.setSelectedFile(new File("gimmick.txt"));// 默认文件名
        chooser.setDialogTitle("保存话术文件（同名直接覆盖）");
        chooser.setFileFilter(new FileNameExtensionFilter("txt", new String[]{"txt"}));
        int result = chooser.showSaveDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            if (null != file) {
                String filePath = file.getAbsolutePath();
                System.out.println("文件保存路径：" + filePath);
                if (null != listener) {
                    listener.onSaveGimmicks(filePath);
                    ((DefaultListModel) othersideListView.getModel()).removeAllElements();
                }

            } else {
                JOptionPane.showMessageDialog(null, "未保存话术文件");
            }
        } else {
            JOptionPane.showMessageDialog(null, "未保存话术文件");
        }
    }

    private void gotoGetSelectedOtherSideGimmick(MouseEvent e, OnListViewItemSelectedListener listener) {
        int index = othersideListView.locationToIndex(e.getPoint());
        String element = (String) othersideListView.getModel()
                                                   .getElementAt(index);
        showPopupMenuInListView(othersideListView, e.getX(), e.getY(), element, listener);
    }

    private void gotoGetSelectedGimmick(MouseEvent e, OnTableItemSelectedListener listener) {
        int rowIndex = gimmickTable.rowAtPoint(e.getPoint());       // 获取点击的行

        String selectedIndex = gimmickTable.getValueAt(rowIndex, 0)
                                           .toString();
        String gimmick = gimmickTable.getValueAt(rowIndex, 1)
                                     .toString();
        String lastIndexs = gimmickTable.getValueAt(rowIndex, 2)
                                        .toString();
        String nextIndexs = gimmickTable.getValueAt(rowIndex, 3)
                                        .toString();
        String side = gimmickTable.getValueAt(rowIndex, 4)
                                  .toString();

        List<String> lastIndexList = UtilListOrString.stringToList(lastIndexs);
        List<String> nextIndexList = UtilListOrString.stringToList(nextIndexs);

        GimmickBean gb = new GimmickBean(selectedIndex, gimmick, lastIndexList, nextIndexList, side);

        gb = gimmickMaster.findGimmick(gb);

        System.out.println("右键点击的行：" + gb.toString());

        showPopupMenuInTable(gimmickTable, e.getX(), e.getY(), gb, listener);
    }

    private void showPopupMenuInTable(Component component, int x, int y, final GimmickBean gb, final OnTableItemSelectedListener listener) {
        JMenuItem deleteMI = new JMenuItem();
        deleteMI.setText("删除本条话术");
        deleteMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("删除");

                int result = JOptionPane.showConfirmDialog(null,
                                                           "执行删除",
                                                           "确认操作",
                                                           JOptionPane.YES_OPTION,
                                                           JOptionPane.QUESTION_MESSAGE);
                if (JOptionPane.YES_OPTION == result) {
                    System.out.println("yes");

                    if (null != listener) {
                        listener.onTableItemSelected(gb, 0);
                    }
                }
            }
        });

        JMenuItem beLlastMI = new JMenuItem();
        beLlastMI.setText("作为'上一条'话术");
        beLlastMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("作为上一条");
                if (null != listener) {
                    listener.onTableItemSelected(gb, 1);
                }
            }
        });

        JMenuItem editMI = new JMenuItem();
        editMI.setText("再次编辑");
        editMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("再次编辑");
                if (null != listener) {
                    listener.onTableItemSelected(gb, 2);
                }
            }
        });

        JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.add(deleteMI);
        popupMenu.addSeparator();
        popupMenu.add(beLlastMI);
        popupMenu.addSeparator();
        popupMenu.add(editMI);

        popupMenu.show(component, x, y);
    }

    private void showPopupMenuInListView(Component component, int x, int y, final String element, final OnListViewItemSelectedListener listener) {
        JMenuItem deleteMI = new JMenuItem();
        deleteMI.setText("移除本条话术");
        deleteMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("删除");

                int result = JOptionPane.showConfirmDialog(null,
                                                           "执行删除",
                                                           "确认操作",
                                                           JOptionPane.YES_OPTION,
                                                           JOptionPane.QUESTION_MESSAGE);
                if (JOptionPane.YES_OPTION == result) {
                    System.out.println("yes");

                    if (null != listener) {
                        listener.onListViewItemSelected(element);
                    }
                }
            }
        });

        JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.add(deleteMI);

        popupMenu.show(component, x, y);
    }

    private void gotoInsertGimmick(OnInsertGimmickListener listener) {
        String text = nextGimmickTextArea.getText();
        if (null == text) {
            JOptionPane.showMessageDialog(null, "请编写话术");
            return;
        }

        String trim = text.trim();
        if (trim.length() < 1) {
            JOptionPane.showMessageDialog(null, "请编写话术");
            return;
        }

        nextGimmickTextArea.setText("");

        if (null != listener) {
            listener.onInsertGimmick(trim);
        }
    }

    private void gotoClearGimmickListView(OnClearGimmickListViewListener listener) {
        List<GimmickBean> list = gimmickMaster.getAllGimmicks();
        if (list.size() > 0) {
            int result = JOptionPane.showConfirmDialog(null,
                                                       "执行清空且不保存",
                                                       "确认操作",
                                                       JOptionPane.YES_OPTION,
                                                       JOptionPane.QUESTION_MESSAGE);
            if (JOptionPane.YES_OPTION == result) {
                System.out.println("yes");
                if (null != listener) {
                    ((DefaultListModel) othersideListView.getModel()).removeAllElements();
                    listener.onClearGimmickListView();
                }
            }
        }
    }

    private void browserWebsite() {
        if (Desktop.isDesktopSupported()) {
            try {
                URI uri = URI.create("http://www.gaohaiyan.com/");
                Desktop dp = Desktop.getDesktop();
                if (dp.isSupported(Desktop.Action.BROWSE)) {
                    dp.browse(uri);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void editGimmickItem(GimmickBean gimmickBean) {
        System.out.println("更新前：" + gimmickBean.hashCode() + "，" + gimmickBean);
        new EditGimmickUI(this,
                          gimmickBean,
                          new EditGimmickUI.OnEditGimmickUIClosedListener() {
                              @Override
                              public void onEditGimmickUIClosed(GimmickBean gb) {
                                  if (null != gb) {
                                      System.out.println("更新后：" + gb.hashCode() + "，" + gb);
                                      gimmickMaster.updateData();      // 再次编辑后更新
                                      flushOtherSideGimmickListView(); // 再次编辑后更新
                                  }
                              }
                          });
    }

    public void addGimmickToOtherSideListView(GimmickBean gimmickBean) {
        System.out.println("添加到对方话术列表：" + gimmickBean);
        flushOtherSideGimmickListView();
    }

    public void removeGimmickFromOtherSideListView(GimmickBean gimmickBean) {
        System.out.println("从对方话术列表删除：" + gimmickBean);
        flushOtherSideGimmickListView();
    }

    private void flushOtherSideGimmickListView() {
        DefaultListModel<String> listModel = (DefaultListModel<String>) othersideListView.getModel();
        listModel.removeAllElements();
        List<GimmickBean> lastGimmicks = gimmickMaster.getAllOthersideGimmicks();
        for (int i = 0; i < lastGimmicks.size(); i++) {
            GimmickBean gimmickBean = lastGimmicks.get(i);
            String index = gimmickBean.getIndex();
            String gimmick = gimmickBean.getGimmick();
            listModel.addElement(index + Constant.OTHERSIDE_SPLITE_FLAG + gimmick);
        }

        JScrollBar scrollBar = otherGimmickListViewPanel.getVerticalScrollBar();
        otherGimmickListViewPanel.getViewport()
                                 .setViewPosition(new Point(0, scrollBar.getMaximum()));
    }

    private DefaultListCellRenderer getListCellRenderer() {
        if (null == listCellRenderer) {
            listCellRenderer = new DefaultListCellRenderer() {
                private Color ffffccColor = new Color(Integer.valueOf("#ffffcc".substring(1), 16));
                private Color ccffffColor = new Color(Integer.valueOf("#ccffff".substring(1), 16));

                @Override
                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                    if (index % 2 == 0) {
                        setBackground(ffffccColor);
                    } else if (index % 2 == 1) {
                        setBackground(ccffffColor);
                    }

                    return this;
                }
            };
        }

        return listCellRenderer;
    }

    public void setMaster(GimmickMaster gimmickMaster) {
        this.gimmickMaster = gimmickMaster;
    }

    public interface OnTableItemSelectedListener {
        public void onTableItemSelected(GimmickBean gimmickBean, int flag);
    }

    public interface OnListViewItemSelectedListener {
        public void onListViewItemSelected(String element);
    }

    public interface OnTableItemDeletedListener {
        public void onTableItemDeleted(GimmickBean gimmickBean, boolean isContainsInOtherSide);
    }

    public interface OnListViewItemDeletedListener {
        public void onListViewItemDeleted(GimmickBean gimmickBean);
    }

    public interface OnAddTableItemToOthersideListener {
        public void onAddTableItemToOtherside(GimmickBean gimmickBean);
    }

    public interface OnLoadGimmicksListener {
        public void onLoadGimmicks(String filePath);
    }

    public interface OnSaveGimmicksListener {
        public void onSaveGimmicks(String filePath);
    }

    public interface OnChattestListener {
        public void onChattest(List<GimmickBean> gimmicks);
    }

    public interface OnResetLastGimmicksListener {
        public void onResetLastGimmicks();
    }

    public interface OnInsertGimmickListener {
        public void onInsertGimmick(String gimmick);
    }

    public interface OnSideItemSelectedListener {
        public void onSideItemSelected(String side);// otherside-O，meside-M
    }

    public interface OnClearGimmickListViewListener {
        public void onClearGimmickListView();
    }
}
